package com.esun.service.auth;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.esun.common.constant.SystemsConstant;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author John.xiao
 * @date 2021/8/2 17:16
 */
@Component
public class StpImpl  implements StpInterface {
	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {
		List<String> roleList = StpUtil.getSessionByLoginId(loginId).get("Role_Id",()-> getRoleList(loginId,loginType));
		List<String> permissionList = new ArrayList<>();
		for (String roleId : roleList){
			SaSession roleSession = SaSessionCustomUtil.getSessionById("role-" + roleId);
			// 从数据库查询这个角色id拥有的权限列表
			List<String> list = roleSession.get("Permission_List", ArrayList::new);
			permissionList.addAll(list);
		}
		return permissionList;
	}

	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		//redis主键
		String redisKey = SystemsConstant.ROLE_PERMISSION_CACHE_PREFIX+loginId.toString().trim();
		SaSession roleSession = SaSessionCustomUtil.getSessionById(redisKey);
		return roleSession.get("Role_Id", ArrayList::new);
	}
}
